//
//  BGJiBenMessageViewController.m
//  bigMall
//
//  Created by ios on 16/7/19.
//  Copyright © 2016年 thinklev. All rights reserved.
//

#import "BGJiBenMessageViewController.h"
#import "BGDateResult.h"
#import "BGJiBenTableViewCell.h"
#import "BGLoginMode.h"
#import "BGProfileViewController.h"
#import "BGfileupload.h"
#import "BGFileUpLoadModel.h"
#import "BGUpdataHeadPhotoModel.h"
#import "BGBasicUrl.h"
#import "UIImageView+WebCache.h"

@interface BGJiBenMessageViewController () <UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate> {
    
    UITableView *_tableView;
    NSArray *_title;
    NSArray *_texts;
    UIImageView *imageView;//头像啊
    UIImage *saveImage;
    UIView *vie;
    NSString *nameStr;
    NSString *idStr;
    NSString *urlStr;
    
}
@end

@implementation BGJiBenMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我的账户";
    
    saveImage = [UIImage imageNamed:@"头像"];
    
    [self createUI];
    [self loadInter];
    [self initDataa];
    
    self.view.backgroundColor = GWColor(244, 244, 244, 244);
    
}

- (void)loadInter {
    
    [BGDateResult getUserInfoSuccess:^(NSString *status, NSString *msg, NSDictionary *res) {
        
        if ([status intValue] == 1) {
            
//            BGLoginMode *model = (BGLoginMode *)res;
            
            _texts = @[res[@"name"]];
            
            NSData *dataImage = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",[BGBasicUrl getBasicUrl],res[@"imgsrc"]]]];
            
            UIImage *image = [UIImage imageWithData:dataImage];
            
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"icon"] == nil && [[NSUserDefaults standardUserDefaults] objectForKey:@"iconName"] == nil)
            {
                
                
                                [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(image) forKey:@"icon"];
                [[NSUserDefaults standardUserDefaults] setObject:res[@"imgsrc"] forKey:@"iconName"];
                                [[NSUserDefaults standardUserDefaults] synchronize];
            
//                [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(saveImage) forKey:@"icon"];
//                [[NSUserDefaults standardUserDefaults] synchronize];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",[BGBasicUrl getBasicUrl],res[@"imgsrc"]]]];
                
            }
            
        }else {
            
            [self showMessage:msg];
            
        }
        
        [_tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)showMessage:(NSString *)message {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    
    [alertController addAction:okAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}
//15376908113
- (void)initDataa {
    
    _title = @[@"用户名"];
    
}

- (void)createUI {
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    
    _tableView.delegate = self;
    
    _tableView.dataSource = self;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:_tableView];
    
    //tableviewcell上要添加的视图
    vie = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BGWidth, 97)];
    
    vie.backgroundColor = [UIColor whiteColor];
    
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(25, (vie.height - 55) / 2, 55, 55)];
//    [imageView addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"imageView_Change"];
    imageView.clipsToBounds = YES;
    //        imageView.layer.backgroundColor = (__bridge CGColorRef _Nullable)([UIColor lightGrayColor]);
    //        imageView.layer.borderWidth = 1;
    imageView.layer.cornerRadius = 27.5;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"icon"] != nil)
    {
    
        saveImage = [UIImage imageWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"icon"]];
    
    }
    imageView.image = saveImage;
    //        if (imageView.image == nil) {
    //
    //        imageView.image = [UIImage imageNamed:@"头像"];
    //
    //        }
    [vie addSubview:imageView];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(imageView.right + 10, (vie.height - 21) / 2, 86, 21)];
    [btn setTitle:@"更改头像" forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    [vie addSubview:btn];
    
}

- (void)click {
    
    UIAlertController *action = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *a1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //拍照
        [self readImageFromCamera];
        
    }];
    [action addAction:a1];
    
    UIAlertAction *a2 = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //从相册中读取
        [self readImageFromAlbum];
        
    }];
    [action addAction:a2];
    
    UIAlertAction *a3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [action addAction:a3];
    
    [self presentViewController:action animated:YES completion:^{
        
    }];
    
}

//从相册中读取
- (void)readImageFromAlbum {
    //创建对象
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    //（选择类型）表示仅仅从相册中选取照片
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //指定代理，因此我们要实现UIImagePickerControllerDelegate,
    //UINavigationControllerDelegate协议
    imagePicker.delegate = self;
    //设置在相册选完照片后，是否跳到编辑模式进行图片剪裁。(允许用户编辑)
    imagePicker.allowsEditing = YES;
    //显示相册
    [self presentViewController:imagePicker animated:YES completion:nil];
    
}
//图片完成之后处理

- (void)imagePickerController:(UIImagePickerController *)picker
        didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    
    //image 就是修改后的照片
    //将图片添加到对应的视图上
    saveImage = image;
    
//    imageView.image = saveImage;
    
    [_tableView reloadData];
    //结束操作
    [self dismissViewControllerAnimated:YES completion:nil];
    [self updataHeader:image];
}

- (void)updataHeader:(UIImage *)headImage {
    
    NSData *fData = UIImageJPEGRepresentation(headImage, 0.1);
    //图片的上传
    NSString *path = [NSString stringWithFormat:@"%@/Api_1/Index/upload",[BGBasicUrl getBasicUrl]];
    //参数列表（字典类型啊）
    NSDictionary *paramters = @{@"obj_id":@"123",@"type":@"mall"};
    [BGfileupload getFileUpLoadPath:path andParamters:paramters andData:fData success:^(NSObject *object) {
        
        BGFileUpLoadModel *model = (BGFileUpLoadModel *)object;
        if ([model.status isEqualToString:@"1"]) {
            
            NSDictionary *res = [NSDictionary dictionaryWithDictionary:model.res];
            NSArray *arr = [res objectForKey:@"arr"];
            NSDictionary *dic = arr[0];
            nameStr = [dic objectForKey:@"name"];
            urlStr = [dic objectForKey:@"url"];
            idStr = [dic objectForKey:@"id"];
            
            [BGDateResult updateHeadPhotoWithimgsrc:urlStr success:^(NSObject *result) {
                
                BGUpdataHeadPhotoModel *model = (BGUpdataHeadPhotoModel *)result;
                
                if ([model.status isEqualToString:@"1"]) {
                    
                   
                        [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(saveImage) forKey:@"icon"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    
                    
                    [self showMessage:model.msg];
                }else {
                    [self showMessage:model.msg];
                }
                
            } failure:^(NSError *error) {
                
            }];

            
        }else {
            
            [self showMessage:model.msg];
            
        }
        
        
    } failure:^(NSError *error) {
        
    }];

}
- (void)readImageFromCamera {
    
    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES; //允许用户编辑
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    } else {
        //弹出窗口响应点击事件
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"未检测到摄像头" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

#pragma mark - datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 97;
    }else {
    return 59;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    //获取indexPath
    NSIndexPath *indexPath = [[NSIndexPath alloc] initWithIndex:section];
    if (0 == indexPath.section) {//第一组
        return 12;
    }else
        return 12;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;//设置尾视图高度为0.01
}
#pragma mark - delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"celId"];
        UITableViewCell *cel = [[UITableViewCell alloc] init];
        cel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        imageView.image = saveImage;
        
        [cel.contentView addSubview:vie];
        
        return cel;
        
    }
    
    [tableView registerNib:[UINib nibWithNibName:@"BGJiBenTableViewCell" bundle:nil] forCellReuseIdentifier:@"celId"];
    
    BGJiBenTableViewCell *cel = [tableView dequeueReusableCellWithIdentifier:@"celId" forIndexPath:indexPath];
    
    cel.title.text = _title[indexPath.row];
    cel.text.text = _texts[0];
    
    return cel;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        [self click];
    }
    
}
//- (void)dealloc {
//    
//    [imageView removeObserver:self forKeyPath:@"image"];
//    
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
